package com.zide.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zide.auth.domain.entity.platform.PlatformRole;
import com.zide.auth.domain.entity.platform.PlatformRoleMenu;
import com.zide.auth.domain.entity.platform.PlatformUser;
import com.zide.auth.domain.entity.platform.PlatformUserRole;
import com.zide.auth.mapper.platform.PlatformRoleMapper;
import com.zide.auth.mapper.platform.PlatformRoleMenuMapper;
import com.zide.auth.mapper.platform.PlatformUserRoleMapper;
import com.zide.auth.utils.ZiDeContext;
import com.zide.auth.vo.search.PlatformRoleSearchVO;
import com.zide.common.constant.UserConstants;
import com.zide.common.core.domain.PageResult;
import com.zide.common.exception.ServiceException;
import com.zide.common.utils.StringUtils;
import com.zide.auth.domain.entity.platform.dept.PlatformRoleDept;
import com.zide.platform.mapper.PlatformRoleDeptMapper;
import com.zide.platform.service.PlatformRoleService;
import com.zide.platform.vo.result.role.PlatformRoleResultVO;
import com.zide.platform.vo.save.PlatformRoleSaveOrUpdateVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色 业务层处理
 *
 * @author xianying
 */
@RequiredArgsConstructor
@Service
public class PlatformRoleServiceImpl implements PlatformRoleService {
    @Autowired
    private final PlatformRoleMapper roleMapper;

    @Autowired
    private final PlatformRoleMenuMapper roleMenuMapper;

    @Autowired
    private final PlatformUserRoleMapper userRoleMapper;

    @Autowired
    private final PlatformRoleDeptMapper roleDeptMapper;

    @Override
    public PageResult<PlatformRoleResultVO> selectRolePage(PlatformRoleSearchVO searchVO) {
        PageResult<PlatformRole> PlatformRolePageResult = roleMapper.selectPage(searchVO);
        PageResult<PlatformRoleResultVO> result = new PageResult<>();
        BeanUtil.copyProperties(PlatformRolePageResult,result);
        return result;

    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<PlatformRoleResultVO> selectRolesByUserId(Long userId) {
        List<PlatformRole> userRoles = roleMapper.selectRolePermissionByUserId(userId);
        List<PlatformRole> roles = selectRoleAll();
        List<PlatformRoleResultVO> PlatformRoleResultVOS = BeanUtil.copyToList(roles, PlatformRoleResultVO.class);
        for (PlatformRoleResultVO role : PlatformRoleResultVOS) {
            for (PlatformRole userRole : userRoles) {
                if (role.getId().longValue() == userRole.getId().longValue()) {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return PlatformRoleResultVOS;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
        List<PlatformRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (PlatformRole perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleCode().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<PlatformRole> selectRoleAll() {
        return roleMapper.selectList();
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Long> selectRoleListByUserId(Long userId) {
        return roleMapper.selectRoleListByUserId(userId);
    }

    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public PlatformRoleResultVO selectRoleById(Long roleId) {
        PlatformRole PlatformRole = roleMapper.selectById(roleId);
        return BeanUtil.copyProperties(PlatformRole,PlatformRoleResultVO.class);
    }

    /**
     * 校验角色名称是否唯一
     * @return 结果
     */
    @Override
    public boolean checkRoleNameUnique(PlatformRoleSaveOrUpdateVO saveVO) {
        Long roleId = StringUtils.isNull(saveVO.getId()) ? -1L : saveVO.getId();
        PlatformRole info = roleMapper.checkRoleNameUnique(saveVO.getRoleName());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     * @return 结果
     */
    @Override
    public boolean checkRoleKeyUnique(PlatformRoleSaveOrUpdateVO saveVO) {
        Long roleId = StringUtils.isNull(saveVO.getId()) ? -1L : saveVO.getId();
        PlatformRole info = roleMapper.checkRoleKeyUnique(saveVO.getRoleCode());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色是否允许操作
     */
    @Override
    public void checkRoleAllowed(PlatformRoleSaveOrUpdateVO saveVO) {
        if (StringUtils.isNotNull(saveVO.getId()) && saveVO.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    /**
     * 校验角色是否有数据权限
     *
     * @param roleId 角色id
     */
    @Override
    public void checkRoleDataScope(Long roleId) {
        if (!PlatformUser.isAdmin(ZiDeContext.getPlatformUserId())) {
            PlatformRole role = new PlatformRole();
            role.setId(roleId);
            List<PlatformRole> roles = roleMapper.selectList();
            if (StringUtils.isEmpty(roles)) {
                throw new ServiceException("没有权限访问角色数据！");
            }
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId) {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    /**
     * 新增保存角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRole(PlatformRoleSaveOrUpdateVO saveVO) {
        PlatformRole insertBean = BeanUtil.copyProperties(saveVO, PlatformRole.class);

        // 新增角色信息
        roleMapper.insert(insertBean);
        saveVO.setId(insertBean.getId());
        return insertRoleMenu(saveVO);
    }

    /**
     * 修改保存角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRole(PlatformRoleSaveOrUpdateVO saveVO) {
        PlatformRole updateBean = BeanUtil.copyProperties(saveVO, PlatformRole.class);
        // 修改角色信息
        roleMapper.updateById(updateBean);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(saveVO.getId());
        return insertRoleMenu(saveVO);
    }

    /**
     * 修改角色状态
     * @return 结果
     */
    @Override
    public int updateRoleStatus(PlatformRoleSaveOrUpdateVO saveVO) {
        PlatformRole updateBean = BeanUtil.copyProperties(saveVO, PlatformRole.class);
        return roleMapper.updateById(updateBean);
    }

    /**
     * 修改数据权限信息
     * @return 结果
     */
    @Override
    @Transactional
    public int authDataScope(PlatformRoleSaveOrUpdateVO saveVO) {
        PlatformRole updateBean = BeanUtil.copyProperties(saveVO, PlatformRole.class);

        // 修改角色信息
        roleMapper.updateById(updateBean);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(saveVO.getId());
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(updateBean);
    }

    /**
     * 新增角色菜单信息
     */
    public int insertRoleMenu(PlatformRoleSaveOrUpdateVO saveVO) {
        int rows = 1;
        // 新增用户与角色管理
        List<PlatformRoleMenu> list = new ArrayList<PlatformRoleMenu>();
        for (Long menuId : saveVO.getMenuIds()) {
            PlatformRoleMenu rm = new PlatformRoleMenu();
            rm.setRoleId(saveVO.getId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public int insertRoleDept(PlatformRole role) {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<PlatformRoleDept> list = new ArrayList<PlatformRoleDept>();
        for (Long deptId : role.getDeptIds()) {
            PlatformRoleDept rd = new PlatformRoleDept();
            rd.setRoleId(role.getId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0) {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }

    /**
     * 通过角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRoleById(Long roleId) {
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(roleId);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(roleId);
        return roleMapper.deleteById(roleId);
    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的角色ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds) {
            PlatformRoleSaveOrUpdateVO saveVO = new PlatformRoleSaveOrUpdateVO();
            saveVO.setId(roleId);
            checkRoleAllowed(saveVO);
            checkRoleDataScope(roleId);
            PlatformRole role = roleMapper.selectById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenu(roleIds);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDept(roleIds);
        return roleMapper.deleteBatchIds(Arrays.asList(roleIds));
    }

    /**
     * 取消授权用户角色
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(PlatformUserRole userRole) {
        return userRoleMapper.deleteUserRoleInfo(userRole);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteAuthUsers(Long roleId, Long[] userIds) {
        return userRoleMapper.deleteUserRoleInfos(roleId, userIds);
    }

    /**
     * 批量选择授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要授权的用户数据ID
     * @return 结果
     */
    @Override
    public int insertAuthUsers(Long roleId, Long[] userIds) {
        // 新增用户与角色管理
        List<PlatformUserRole> list = new ArrayList<>();
        for (Long userId : userIds) {
            list.add(new PlatformUserRole(userId,roleId));
        }
        return userRoleMapper.batchUserRole(list);
    }
}
